<?php

class Auth_Adapter_Basic extends Auth_Adapter_Cookie implements Zend_Auth_Adapter_Interface
{
	
	/**
	 * Username from User table for auth
	 *
	 * @var string
	 */
	private $_username;

	/**
	 * Password from User table for auth
	 *
	 * @var string
	 */
	private $_password;

	/**
	 * Phone number (msisdn) from User table for auth by passport
	 *
	 * @var string
	 */	
	private $_msisdn;
	
	/**
	 * пароль это уже хеш
	 * @var boolean
	 */
	private $_pass_is_hash;

	/**
     * Sets username and password for authentication
     *
     * @param string $username Email, login or phone
     * @param string Unhashed password
     * @return void
     */
    public function __construct($username, $password, $msisdn = null, $params = array())
    {
        $this->_username = $username ? $username : null;
        $this->_password = $password ? $password : null;
        $this->_msisdn = $msisdn ? $msisdn : null;
        if (isset($params['pass_is_hash']) && $params['pass_is_hash']) {
        	$this->_pass_is_hash = true;
        } else {
        	$this->_pass_is_hash = false;
        }
    }

    /**
     * Performs an authentication attempt
     *
     * @throws Zend_Auth_Adapter_Exception If authentication cannot be performed
     * @return Zend_Auth_Result
     */
    public function authenticate()
    {
    	$profilePeer = ProfilePeer::getInstance();
    	$select = $profilePeer->select();
    	
    	$code = Zend_Auth_Result::FAILURE;
    	$identity = null;
    		$userName = trim($this->_username);
    		$password = $this->_password;
    		
    		//проверяем на пустоты в параметрах
    		if (empty($userName) || empty($password)) {
    			return new Zend_Auth_Result($code, null, array());
    		}
    		
    		
    		//логин можно осуществлять и по email
    		$condColumn = ProfilePeer::EMAIL;
//	    	if ($emailRule->Validate(array('email' => $userName))) {
//	    		$condColumn = ProfilePeer::EMAIL;
//	    	}
	    	$select->where($condColumn.' = ?', $userName);
	    	$profileRow = $profilePeer->fetchRow($select);
	    	
	    	//проверка пароля на уровне проекта
	    	if ($profileRow) {
	    		$basePasswd = $profileRow->getPassword();
	    		$password = ProfileService::getInstance()->encryptSha1Password($password);
	    		if ($password == $basePasswd) { //проверям пару логин пароль
	    			$code = Zend_Auth_Result::SUCCESS;
	    		}
	    	} else {
	    		$code = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
	    	}
    	
    	if (Zend_Auth_Result::SUCCESS == $code) {
    		$identity = $profileRow->getId();
			$this->_saveInCookie($profileRow);
    	}
    	
    	return new Zend_Auth_Result($code, $identity, array());
    }
}